package com.xy6.dpdemo.book.chapter14.observer.event;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

/**
 * 事件源对象
 * <p>控制开门、关门的控制器，类似一个button
 * 
 * @author zhang
 *
 */
public class DoorManager {

	private Collection<IDoorListener> listeners;

	/**
	 * 添加事件
	 * 
	 * @param listener
	 */
	public void addDoorListener(IDoorListener listener) {
		if (null == listeners) {
			listeners = new HashSet<IDoorListener>();
		}
		listeners.add(listener);
	}

	/**
	 * 移除事件
	 * 
	 * @param listener
	 */
	public void removeDoorListener(IDoorListener listener) {
		if (listeners == null)
			return;
		listeners.remove(listener);
	}

	/**
	 * 开门
	 */
	protected void fireWorkspaceOpened() {
		if (listeners == null)
			return;
		DoorEvent event = new DoorEvent(this, "open");
		notifyListeners(event);
	}

	/**
	 * 关门
	 */
	protected void fireWorkspaceClosed() {
		if (listeners == null)
			return;
		DoorEvent event = new DoorEvent(this, "close");
		notifyListeners(event);
	}

	/**
	 * 发布通告，通知所有监听器
	 * 
	 * @param event
	 */
	private void notifyListeners(DoorEvent event) {
		Iterator<IDoorListener> iter = listeners.iterator();
		while (iter.hasNext()) {
			IDoorListener listener = (IDoorListener) iter.next();
			listener.doorEvent(event);
		}
	}

}
